import React, { useState, useImperativeHandle, useEffect, useMemo, useRef } from "react";
import { TextBox } from 'devextreme-react';

const PTextBox: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { defaultValue } = props;

    const [value, setValue] = useState("");
    const boxValue = useRef<any>('');
    const textBoxRef = useRef<any>();



    useEffect(() => {
        setValue(defaultValue);
        boxValue.current = defaultValue;
    }, [defaultValue]);

    const handleChange = (e: any) => {
        console.log(e, '@@@');
        const { event } = e;
        console.log(event.target.value, '@@@');
        boxValue.current = event.target.value;
        setValue(event.target.value);
        props.changeData(event.target.value);
    };

    const findValue = () => {
        console.log(boxValue.current, '@@@');
        return boxValue.current;
    }

    useImperativeHandle(ref, () => ({
        initValue: (value: any) => setValue(value),
        getValue: () => findValue(),
        focusTextBox: () => {
            if (textBoxRef.current) {
                textBoxRef.current.instance.focus();
            }
        }
    }));

    const handleKeyDown = (e: any) => {
        if (e.event.keyCode === 13) {
            e.event.preventDefault();
            if (props?.onKeyDownTextBox) {
                props?.onKeyDownTextBox();
            }
        }

    };


    return <>
        {
            useMemo(() => {
                return <TextBox ref={textBoxRef} value={value}
                    onChange={handleChange}
                    onKeyDown={handleKeyDown}
                />
            }, [value])
        }
    </>;
});

export default PTextBox;
